package fr.cdj.thebox.client.menu.ui;

import com.google.gwt.event.logical.shared.HasValueChangeHandlers;
import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.user.client.Event;
import com.google.gwt.user.client.ui.HasVerticalAlignment;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.SimplePanel;
import com.google.gwt.user.client.ui.TextBox;
import com.google.inject.Inject;
import com.google.inject.Provider;

import fr.cdj.thebox.client.resources.TheboxBundle;
import fr.cdj.thebox.client.utils.Icon;

public class SearchItem extends SimplePanel implements HasValueChangeHandlers<String> {

	private class SearchTextBox extends TextBox {
		private String oldValue;

		public SearchTextBox() {
			sinkEvents(Event.ONPASTE | Event.ONKEYUP);
			oldValue = this.getValue();
		}

		@Override
		public void onBrowserEvent(Event event) {
			super.onBrowserEvent(event);
			switch (event.getTypeInt()) {
			case Event.ONKEYUP:
			case Event.ONPASTE:
				ValueChangeEvent.fireIfNotEqual(this, oldValue, this.getValue());
				break;
			}
			oldValue = this.getValue();
		}
	}

	private SearchTextBox searchBox;

	@Inject
	public SearchItem(TheboxBundle resources, Provider<Icon> iconProvider) {
		this.setStyleName(resources.getStyle().menuItem());
		
		HorizontalPanel hPanel = new HorizontalPanel();
		hPanel.setSize("100%", "100%");
		hPanel.setVerticalAlignment(HasVerticalAlignment.ALIGN_MIDDLE);
		
		Icon searchIcon = iconProvider.get();
		searchIcon.addStyleName(resources.getStyle().search());
		searchBox = new SearchTextBox();
		searchBox.setStyleName(resources.getStyle().searchInput());
		
		hPanel.add(searchIcon);
		hPanel.add(searchBox);
		this.add(hPanel);
	}

	@Override
	public HandlerRegistration addValueChangeHandler(ValueChangeHandler<String> handler) {
		return searchBox.addValueChangeHandler(handler);
	}

}
